标签
测试
字数
1606 字
阅读时间
7 分钟
一、基本使用
单元测试就是针对最小的功能单元编写测试代码,Java程序最小的功能单元是方法,因此,单元测试就是针对Java方法的测试,进而检查方法的正确性。
1.1 junit单元测试
java
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CalculatorTest {
/**
* 初始化方法:
* 用于资源申请,所有测试方法在执行之前都会先执行该方法
*/
@Before
public void init(){
System.out.println("init...");
}
/**
* 释放资源方法:
* 在所有测试方法执行完后,都会自动执行该方法
*/
@After
public void close(){
System.out.println("close...");
}
/**
* 测试add方法
*/
@Test
public void testAdd(){
// System.out.println("我被执行了");
//1.创建计算器对象
System.out.println("testAdd...");
// 逻辑
//System.out.println(result);
//3.断言 我断言这个结果是3
Assert.assertEquals(3,result);
}
@Test
public void testSub(){
System.out.println("testSub....");
Assert.assertEquals(-1,result);
}
}1.2 SpringBoot单元测试
1. 常规方式
java
// classes 不指定使用默认的引导类,还可使用@ContextConfiguration指定引导类
@SpringBootTest(classes = Springboot04JunitApplication.class)
//@ContextConfiguration(classes = Springboot04JunitApplication.class)
class Springboot04JunitApplicationTests {
//注入你要测试的对象
@Autowired
private BookDao bookDao;
@Test
void contextLoads() {
//执行要测试的对象对应的方法
bookDao.save();
System.out.println("two...");
}
}2. 指定临时属性 和临时参数
java
//properties属性可以为当前测试用例添加临时的属性配置
//args属性可以为当前测试用例添加临时的命令行参数
@SpringBootTest(properties = {"test.prop=testValue1"},args={"--test.prop=testValue2"})
public class PropertiesAndArgsTest {
@Value("${test.prop}")
private String msg;
@Test
void testProperties(){
System.out.println(msg);
}
}3. 加载专用配置
java
@SpringBootTest
// MsgConfig是测试环境专用的配置类。
@Import({MsgConfig.class})
public class ConfigurationTest {
@Autowired
private String msg;
@Test
void testConfiguration(){
System.out.println(msg);
}
}4. 数据层测试回滚
测试的数据再测试用例运行结束后直接回滚,不在系统中留垃圾数据。
只要注解@Transactional出现的位置存在注解@SpringBootTest,springboot就会认为这是一个测试程序,无需提交事务。
如果想提交事务,添加一个@RollBack的注解,设置回滚状态为false即可正常提交事务。
java
@SpringBootTest
@Transactional
@Rollback(true)
public class DaoTest {
@Autowired
private BookService bookService;
@Test
void testSave(){
Book book = new Book();
book.setName("springboot3");
book.setType("springboot3");
book.setDescription("springboot3");
bookService.save(book);
}
}5. 测试随机数据
yaml
testcase:
book:
id: ${random.int} #随机整数
id2: ${random.int(10)} #10以内随机数
type: ${random.int!5,10!} #
name: ${random.value} # 随机字符串
uuid: ${random.uuid} # 随机uuid
publishTime: ${random.long} # 随机整数 long范围当前配置就可以在每次运行程序时创建一组随机数据,避免每次运行时数据都是固定值的尴尬现象发生。加载数据使用@ConfigurationProperties注解。加载到实体类中。
1.3 Web环境模拟测试
测试类中启动web环境
java// webEnvironment可以设置在测试用例中启动web环境。 //MOCK:根据当前设置确认是否启动web环境,例如使用了Servlet的API就启动web环境,属于适配性的配置 //DEFINED_PORT:使用自定义的端口作为web服务器端口 //RANDOM_PORT:使用随机端口作为web服务器端口 //NONE:不启动web环境 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class WebTest { }测试类中发送请求。
java@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //开启虚拟MVC调用 @AutoConfigureMockMvc public class WebTest { @Test void testWeb(@Autowired MockMvc mvc) throws Exception { //创建虚拟请求,当前访问/books // 服务器IP地址和端口使用的是当前虚拟的web环境,无需指定,仅指定请求的具体路径即可。 MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/books"); //执行对应的请求 ResultActions action = mvc.perform(builder); // 响应状态码 //设定预期值 与真实值进行比较,成功测试通过,失败测试失败 //定义本次调用的预期值 StatusResultMatchers status = MockMvcResultMatchers.status(); //预计本次调用时成功的:状态200 ResultMatcher ok = status.isOk(); //添加预计值到本次调用过程中进行匹配 action.andExpect(ok); // 响应体非json数据格式) //设定预期值 与真实值进行比较,成功测试通过,失败测试失败 //定义本次调用的预期值 ContentResultMatchers content = MockMvcResultMatchers.content(); ResultMatcher result = content.string("springboot2"); //添加预计值到本次调用过程中进行匹配 action.andExpect(result); // 响应体,json格式 //设定预期值 与真实值进行比较,成功测试通过,失败测试失败 //定义本次调用的预期值 ContentResultMatchers content = MockMvcResultMatchers.content(); ResultMatcher result = content.json("{\"id\":1,\"name\":\"springboot2\",\"type\":\"springboot\"}"); //添加预计值到本次调用过程中进行匹配 action.andExpect(result); // 响应头 //设定预期值 与真实值进行比较,成功测试通过,失败测试失败 //定义本次调用的预期值 HeaderResultMatchers header = MockMvcResultMatchers.header(); ResultMatcher contentType = header.string("Content-Type", "application/json"); //添加预计值到本次调用过程中进行匹配 action.andExpect(contentType); } }
二、基础知识
测试分类: 1. 黑盒测试:不需要写代码,给输入值,看程序是否能够输出期望的值。 2. 白盒测试:需要写代码的。关注程序具体的执行流程。
2.1 使用步骤
- 定义一个测试类(测试用例)和类中可单独执行的方法
- 给方法加@Test
- 判定结果:红色:失败,绿色:成功 一般我们会使用断言操作来处理结果 Assert.assertEquals(期望的结果,运算的结果);
2.2 Junit常用注解(Junit4版本)
java
@Before:用来修饰方法,该方法会在每一个测试方法执行之前执行一次。
@After:用来修饰方法,该方法会在每一个测试方法执行之后执行一次。
@BeforeClass:用来静态修饰方法,该方法会在所有测试方法之前执行一次。
@AfterClass:用来静态修饰方法,该方法会在所有测试方法之后执行一次。2.3 Junit常用注解(Junit5版本)
java
@BeforeEach:用来修饰方法,该方法会在每一个测试方法执行之前执行一次。
@AfterEach:用来修饰方法,该方法会在每一个测试方法执行之后执行一次。
@BeforeAll:用来静态修饰方法,该方法会在所有测试方法之前执行一次。
@AfterAll:用来静态修饰方法,该方法会在所有测试方法之后执行一次。